import { ApiRes } from '@/types/data'
import { Profile } from '@/types/user'
import request from '@/utils/request'
import useStore from '..'

import { removeProfile, setProfile, getProfile } from '@/utils/storage'
import { defineStore } from 'pinia'
export default defineStore({
  id: 'user',
  // 状态
  state: () => ({
    // 用户信息
    profile: getProfile()
  }

  ),
  // 方法
  actions: {
    // 用户名和密码登录
    async login(account: string, password: string) {
      const res = await request.post<ApiRes<Profile>>('/login', {
        account,
        password,
      })
      // 1. 保存用户信息到 state 中
      this.profile = res.data.result
      setProfile(res.data.result)
    },
    // 短信获取验证码
    async sendMobileMsg(mobile: string) {
      await request.get('/login/code', {
        params: {
          mobile
        }
      })
    },
    async mobileLogin(mobile: string, code: string) {
      const res = await request.post<ApiRes<Profile>>('/login/code', {
        mobile,
        code
      })
      // 保存用户信息到 state中
      this.profile = res.data.result
    },
    // 退出
    async logut() {
      this.profile = {} as Profile
      removeProfile()
      // 清空购物车数据
      const { cart } = useStore()
      cart.clearCart()
    }

  },

},

)
